package com.heima.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.constants.admin.AdminConstants.AdminConstants;
import com.heima.common.exception.CustException;
import com.heima.common.exception.CustomException;
import com.heima.feigns.ArticleFeign;
import com.heima.feigns.WemediaFeign;
import com.heima.model.article.pojos.ApAuthor;
import com.heima.model.common.dtos.PageResponseResult;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.AuthDTO;
import com.heima.model.user.pojos.ApUser;
import com.heima.model.user.pojos.ApUserRealname;
import com.heima.model.wemedia.pojos.WmUser;
import com.heima.user.mapper.ApUserMapper;
import com.heima.user.mapper.ApUserRealnameMapper;
import com.heima.user.service.ApUserRealnameService;
import io.seata.spring.annotation.GlobalTransactional;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class ApUserRealnameServiceImpl extends ServiceImpl<ApUserRealnameMapper, ApUserRealname>
        implements ApUserRealnameService {
    /**
     * 查询列表
     * @param dto
     * @return
     */
    @Override
    public ResponseResult loadListByStatus(AuthDTO dto) {
        //参数检查
        if (dto==null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID);
        }
        dto.checkParam();
        //条件查询
        IPage<ApUserRealname> page = new Page<>(dto.getPage(),dto.getSize());
        LambdaQueryWrapper<ApUserRealname> wrapper = new LambdaQueryWrapper<>();
        if (dto.getStatus()!=null){
            wrapper.eq(ApUserRealname::getStatus,dto.getStatus());
        }
        IPage<ApUserRealname> realnameIPage = this.page(page, wrapper);
        //返回结果
        return new PageResponseResult(dto.getPage(),dto.getSize(),
                realnameIPage.getTotal(),realnameIPage.getRecords());
    }

    @Autowired
    ApUserMapper apUserMapper;

    @GlobalTransactional
    @Override
    public ResponseResult updateStatusById(AuthDTO dto, Short status) {
        //检查参数
        //检查id
        if (dto.getId()==null){
            throw new CustomException(AppHttpCodeEnum.PARAM_INVALID,"实名认证id信息不能为空");
        }
        //根据id查询实名认证信息
        ApUserRealname userRealname = this.getById(dto.getId());
        //检查状态  1:待审核 2:未通过 9:通过
        if (userRealname.getStatus().equals(AdminConstants.WAIT_AUTH)){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"实名认证状态错误");
        }
        //查询关联的apUser信息
        ApUser apUser = apUserMapper.selectById(userRealname.getUserId());
        if (apUser==null){
            throw new CustomException(AppHttpCodeEnum.DATA_NOT_EXIST,"实名认证关联的APP用户信息不存在");
        }
        //修改实名认证的状态
        userRealname.setStatus(status);
        if (StringUtils.isBlank(dto.getMsg())){
            userRealname.setReason(dto.getMsg());
        }
        this.updateById(userRealname);
        //判断是否通过  通过为:9
        if (AdminConstants.PASS_AUTH.equals(userRealname.getStatus())){
            //远程创建自媒体账户
            WmUser wmUser = createWmUser(apUser);
            //创建作者信息
            createApAuthor(wmUser);
        }
        //更新APP用户状态
        apUser.setFlag((short) 1);
        apUserMapper.updateById(apUser);
        //返回结果
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    @Autowired
    WemediaFeign wemediaFeign;

    public WmUser createWmUser(ApUser apUser){
        //查询关联自媒体用户是否已经创建
        ResponseResult<WmUser> result = wemediaFeign.findByName(apUser.getName());
        if (result.getCode().intValue()!=0) {
            CustException.cust(AppHttpCodeEnum.REMOTE_SERVER_ERROR,result.getErrorMessage());
        }
        WmUser wmUser = result.getData();
        //判断自媒体账号是否存在
        if (wmUser!=null){
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"账户已存在");
        }
        //创建自媒体账户
        wmUser = new WmUser();
        wmUser.setName(apUser.getName());
        wmUser.setSalt(apUser.getSalt());  // 盐
        wmUser.setPassword(apUser.getPassword()); // 密码
        wmUser.setPhone(apUser.getPhone());
        wmUser.setCreatedTime(new Date());
        wmUser.setType(0); // 个人
        wmUser.setApUserId(apUser.getId());  // app端用户id
        wmUser.setStatus(AdminConstants.PASS_AUTH.intValue());
        ResponseResult<WmUser> saveResult = wemediaFeign.save(wmUser);
        if(saveResult.getCode().intValue()!=0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,saveResult.getErrorMessage());
        }
        return saveResult.getData();
    }

    @Autowired
    ArticleFeign articleFeign;
    /**
     * 4.2 创建作者信息
     * @param wmUser
     * @return
     */
    private void createApAuthor(WmUser wmUser) {
        //1 检查是否成功调用
        ResponseResult<ApAuthor> apAuthorResult = articleFeign.findByUserId(wmUser.getApUserId());
        if(apAuthorResult.getCode().intValue() != 0){
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,apAuthorResult.getErrorMessage());
        }
        //2. 检查作者信息是否已经存在
        ApAuthor apAuthor = apAuthorResult.getData();
        if (apAuthor != null) {
            CustException.cust(AppHttpCodeEnum.DATA_EXIST,"作者信息已存在");
        }
        //3. 添加作者信息
        apAuthor = new ApAuthor();
        apAuthor.setCreatedTime(new Date());
        apAuthor.setName(wmUser.getName());
        apAuthor.setType(2); // 自媒体人类型
        apAuthor.setUserId(wmUser.getApUserId()); // APP 用户ID
        apAuthor.setWmUserId(wmUser.getId()); // 自媒体用户ID
        ResponseResult result = articleFeign.save(apAuthor);
        //4. 结果失败，抛出异常
        if (result.getCode() != 0) {
            CustException.cust(AppHttpCodeEnum.SERVER_ERROR,result.getErrorMessage());
        }
    }
}
